﻿using System;
using System.Threading;

namespace 信号量
{
    internal class Program
    {
        private static readonly Semaphore semaphore 
            = new Semaphore(initialCount: 3, maximumCount: 3);
        private static int sum = 0;
        private static int total = 10;

        static void Main(string[] args)
        {

            for(int i = 0; i < 20;i++)
            {
                Thread thread = new Thread(ThreadMethod);
                thread.Start();
                thread.Join();
            }
            Console.WriteLine($"最后的结果:sum:{sum}");
        }


        static void ThreadMethod()
        {
            semaphore.WaitOne(); // 等待获取信号量  
            try
            {
                // 临界区代码，只有一个线程可以执行这部分代码  
                for(int i = 0;i < total;i++)
                {
                    sum += 1;
                    Console.WriteLine($"sum:{sum}");
                }
            }
            finally
            {
                // 确保信号量被释放  
                semaphore.Release();
            }
        }
    }
}
